package com.ksana.bean.factory.support;

import com.ksana.bean.BeanException;
import com.ksana.bean.factory.config.BeanDefinition;
import com.ksana.bean.factory.config.ConfigurableListableBeanFactory;

import java.util.HashMap;
import java.util.Map;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory {
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    public Object registerBean(String beanName, BeanDefinition beanDefinition) throws BeanException {
        return beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeanException {
        return beanDefinitionMap.get(beanName);
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeanException {
        Map<String, T> result = new HashMap<>();

        for (String beanName : beanDefinitionMap.keySet()) {
            if (type.isAssignableFrom(beanDefinitionMap.get(beanName).getBean())) {
                Object beanInstance = getBean(beanName);
                result.put(beanName, (T) beanInstance);
            }
        }

        return result;
    }
}
